%% WADENOWGeneral
%
% General script for the Continuous Wavelet and Deep Learning based 
% rainfall/velocity time series classification for nowcasting purposes.
% This scripts allows the guided execution of these steps:
%
%   1) Rainfall and velocity time series inspection and possible cleaning
%      of false velocity peaks, i.e. peaks not due to rainfall.
%      This initial step is not compulsory and could be carried out 
%      before the execution of this script. The called function is
%           PluVelInspect
%
%   2) Scalogram computation for rainfall and velocity time series or 
%      rainfall only time series. A menu box allows the choice between 
%      rainfall and velocity scalograms and rainfall only scalograms.
%      The called function is
%           PluVelScalogram
%
%   3) Trend classification of the basis of user-defined thresholds.
%      The called function is
%           trendClass        
%
%   4) Data homogeneization and augmentation is order to allow training
%      with balanced datasets.
%      The called function is
%           dataHomAug
%
%   5) Scalogram images partition into training, validation ad test 
%      Datasets. The called function is
%           dataTVT
%
%   6) Transfer learning of an available trained CNN model, chosen among
%      alexnet, VGG16, VGG19, googlenet, resnet18, with the scalogram
%      images. The called function is
%           TRLearnPluVel
%      Please note that:
%      (a) the transfer learning of a CNN model requires the installation 
%          of the corresponding support package (a warning message is shown
%          if an unavailable model is called);
%      (b) in case of training resume, the function TRLearnPluVel should be 
%          directly used.
%
% All the parameters required for the computations can be interactively 
% managed by means of an input dialog box.
%
% See also PluVelInspect, PluVelScalogram, trendClass, dataTVT, 
%   TRLearnPluVel. 

% G. Teza, 2020

mennin = menu('IS IT ALSO NECESSARY TO INSPECT THE TIME SERIES?',...
    'YES',...
    'NO, THE NECESSARY FILE IS ALWAYS AVAILABLE',...
    'EXIT');
if mennin == 1
    
    [fileR,pathR] = uigetfile('.mat','Cumulative rainfall time series file');
    fileR = fullfile(pathR,fileR);
    Rain = load(fileR);
    try
        MR1 = Rain.MR1;
        MR7 = Rain.MR7;
    catch
        disp('The selected file must contain the fields MR1 and MR7');
        return
    end
    [fileV,pathV] = uigetfile('.mat','Velocity time series file');
    fileV = fullfile(pathV,fileV);
    Vel = load(fileV);
    try
        MV = Vel.MV;
    catch
        disp('The selected file must contain the field MV');
        return
    end
    tR = MR1(:,1);
    tV = MV(:,1);
    d1ref = max(tR(1),tV(1));
    d2ref = min(tR(end),tV(end));
    
    options.Resize = 'on';
    options.WindowStyle = 'normal';
    options.Interpreter = 'tex';
    promptPV = {'Initial date (serial number):','Final date (serial number):'};
    namePV = 'TIME SERIES LIMITS';
    defaultPV = {num2str(d1ref),nom2str(d2ref)};
    answerPV = inputdlg(promptPV,namePV,1,defaultPV,options);
    d1 = round(str2double(answerPV{1}));
    if isnan(d1), d1 = d1ref; end
    d2 = round(str2double(answerPV{2}));
    if isnan(d2), d2 = d2ref; end
    
    %----------------------------------------------------------------------
    PluVel = PluVelInspect(MR1,MR7,MV,d1,d2);
    %----------------------------------------------------------------------
    
elseif mennin == 2
    
    [filena,pathna] = uigetfile('.mat','Rainfall-Velocity time series file');
    PVfile = fullfile(pathna,filena);
    PluVelS = load(PVfile);
    PluVel = PluVelS.PluVel;

else
    
    return

end

ParamWN = DefParamInteractive(PluVel);

menusc = menu('COMPUTE SCALOGRAMS:',...
    'BASED ON BOTH RAINFALL AND VELOCITY DATA',...
    'BASED ON RAINFALL DATA ONLY');
if menusc == 1
    sigScalo = PluVel;
else
    sigScalo = PluVel(:,1:2);
    sigmaDA = SigmaDA(1);
end

% Scalogram generation ----------------------------------------------------
SigSegmData = PluVelScalogram(sigScalo,ParamWN);
%--------------------------------------------------------------------------

% Scalogram classification ------------------------------------------------
[L,NL,T] = trendClass(PluVel,SigSegmData,ParamWN);
%--------------------------------------------------------------------------

% Data homogeization and augmentation -------------------------------------
[IMDS,SLC,Tout] = dataHomAug(PluVel,SigSegmData,L,T,ParamWN);
%--------------------------------------------------------------------------

% Image datastore partition -----------------------------------------------
[TrainDS,ValDS,TestDS] = dataTVT(IMDS,ParamWN,1);
%--------------------------------------------------------------------------

mensaDS = menu('DO YOU WANT TO SAVE IMAGE DATASTORES?','YES','NO');
if mensaDS == 1
    [fileDS, pathDS] = uiputfile( ...
       {'*.mat','MAT-files (*.mat)'}, ...
        'SAVE DATASTORE FILE', 'TrainValTestDS.mat');
    DSfile = fullfile(pathDS,fileDS);
    if ischar(DSfile)
        save(DSfile,'TrainDS','ValDS','TestDS');
    end
end

% Training ----------------------------------------------------------------
net = TRLearnPluVel([],TrainDS,ValDS,TestDS);
%--------------------------------------------------------------------------

mensanet = menu('DO YOU WANT TO SAVE THE CNN FILE?','YES','NO');
if mensanet == 1
    [fileN, pathN] = uiputfile( ...
       {'*.mat','MAT-files (*.mat)'}, ...
        'SAVE CNN FILE', 'CNNFile.mat');
    netfile = fullfile(pathN,fileN);
    if ischar(netfile)
        save(netfile,'net');
    end
end